<?php

namespace App\Models;

use App\Handlers\KeysHandler;
use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Account extends Model
{
    use SoftDeletes;
    use HasDateTimeFormatter;

    const HIDE = 0;
    const SHOW = 1;

    const SYSTEM_WITHDRAWAL = 0;   // 系统扣款
    const SYSTEM_RECHARGE = 1; // 系统充值
    const RECHARGE = 2;//充值
    const WITHDRAWAL = 3;//提现
    const WITHDRAWAL_FAIL = 4;//提现失败
    //const COMMISSION = 5; // 团队佣金
    //const PRIZE = 6; // 抽奖
    const GOODS_ORDER_PAYMENT = 7; //商品订单付款
    const GOODS_ORDER_REFUND = 8; //商品订单利润返还
    //const RETURN_MONEY = 9;//抢购失败，返还本金
    //const INTEREST = 10;//抢购利息
    //const SOLD = 11;//寄售
    //const REWARD = 12;  // 活动奖励
    //const REWARD_INVITE = 13;  // 邀请活动奖励
    //const SELL_GOODS = 14;  // 邀请活动奖励
    //const GRAB_ORDER_PAYMENT = 15; //抢购订单付款
    //const GRAB_ORDER_RETURN = 16; //抢购订单返还
    //const GRAB_ORDER_COMMISSION = 17; //抢购订单付款
    const AD_COST = 30; //抢购订单付款

    protected $fillable = [
        'order_id',
        'type',
        'user_id',
        'child_user_id',
        'amount',
        'rebate_rate',
        'level',
        'created_at',
        'updated_at',
        'deleted_at'
    ];


    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function childUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'child_user_id', 'id');
    }

    public static function getIncome($uid)
    {
        $key = sprintf('user%d_income', $uid);
        $income = Cache::get($key);
        if (!$income) {
            $income = self::query()->where('user_id', '=', $uid)
                ->where('amount', '>', 0)
                ->sum('amount');
            Cache::put($key, $income, 60 * 2);
        }
        return $income;
    }

    public static function getExpenditure($uid)
    {
        $key = sprintf('user%d_expenditure', $uid);
        $expenditure = Cache::get($key);
        if (!$expenditure) {
            $expenditure = self::query()->where('user_id', '=', $uid)->where('amount', '<', 0)->sum('amount');
            Cache::put($key, $expenditure, 60 * 2);
        }
        return $expenditure;
    }


    /**
     *
     * 购买订单给上级分佣
     * @param GoodsOrder $order
     */
    public function calculateRebate(GoodsOrder $order): void
    {
        if (!Configuration::getItem('commission')) {
            info('佣金分成关闭，订单 ' . $order->id . ' 不分成');
            return;
        }
        $user = User::findOrFail($order->user_id);
        $parent_ids = array_filter(explode(',', trim($user->relation, ',')));
        $three_upper_rebate_rate = array_values(array_filter(explode(',', Configuration::getItem('three_upper_rebate_rate'))));
        if ($parent_ids && $three_upper_rebate_rate) {
            $index = 1;
            while (count($parent_ids)) {
                $uid = array_pop($parent_ids);
                $rule = array_shift($three_upper_rebate_rate);
                $amount = bcmul($order->orderDetail->interest, bcdiv($rule, 100, 2), 2);
                // 如果已经给用户佣金，则此次不给用户返佣金
                $account = Account::query()->where('user_id', $uid)
                    ->where('order_id', $order->id)
                    ->where('type', self::COMMISSION)
                    ->first();
                if ($account) {
                    continue;
                }
                DB::transaction(function () use ($uid, $amount, $user, $order, $index, $rule) {
                    User::findOrFail($uid)->increment('balance', $amount);
                    (new self())->store($uid, $amount, self::COMMISSION, $user->id, $order->id, $index, $rule);
                });
                //增加会员统计的返佣信息
                $user_statistic = UserStatistic::query()->where('user_id', '=', $uid)->first();
                if ($user_statistic) {
                    $user_statistic->increment('commission', $amount);
                    //增加下级购买人数
                    if ($index == 1 && $user->is_purchase == User::PURCHASE_GOODS_NO) {
                        $user->is_purchase = User::PURCHASE_GOODS_YES;
                        $user->save();
                        $user_statistic->increment('one_level_purchase', 1);
                        //修改会员VIP
                        /* 20220927 注释根据下级人数升级VIP代码,修改为根据充值金额升级
                        $vip = Vip::getBySubordinateNumber($user_statistic->one_level_purchase);
                        $parent_user = User::findOrFail($uid);
                        if ($vip->value > $parent_user->vip->value) {
                            $parent_user->vip_id = $vip->id;
                            $parent_user->save();
                        }
                        */
                    }
                }
                $index++;
            }
            $order->is_commission = true;
            $order->save();
        }
    }

    /**
     * 账目明细
     * @param $user_id
     * @param $type
     * @param int $page 页码
     * @param int $limit 每页条数
     * @param string $date 日期  Y-m(2020-12)
     * @return Builder[]|Collection
     */
    public function getAccounts($user_id, $type, int $page = 1, int $limit = 10, string $date = '')
    {
        $key = sprintf(KeysHandler::USER_ACCOUNT, $user_id, $type, $page, $limit, $date ?: '');
        $rows = Cache::get($key);
        if (!$rows) {
            $rows = self::query()
                ->when($date, function ($query) use ($date) {
                    $query->whereBetween('created_at', [
                        Carbon::parse($date)->firstOfMonth(),
                        Carbon::parse($date)->lastOfMonth()->addDay(),
                    ]);
                })
                ->when($type >= 0, function (Builder $query) use ($type) {
                    $query->where('type', '=', $type);
                })
                ->where('user_id', '=', $user_id)
                ->select('id', 'type', 'amount', 'child_user_id', 'created_at','order_id')
                ->offset($page)->limit($limit)
                ->orderBy('created_at', 'desc')
                ->orderBy('id', 'desc')
                ->get();

            //判断是否有充值类型的
            if($type <0 || $type==self::RECHARGE){
                $orderlist = Order::query()->where('type','=',Order::RECHARGE)->where('user_id','=',$user_id)->pluck('remark','id')->toArray();
                if(!empty($orderlist)){
                    foreach ($rows as &$acc){
                        $acc->type_str = "";
                        if($acc->type == self::RECHARGE){
                            $acc->type_str = $orderlist[$acc->order_id]??"";
                        }
                    }
                }

            }


            Cache::put($key, $rows, 30);
        }

        return $rows;
    }

    /**
     * 创建流水
     * @param $user_id
     * @param $amount
     * @param $type
     * @param int $child_user_id
     * @param int $order_id
     * @param int $level
     * @param int $rebate_rate
     */
    public function store($user_id, $amount, $type, int $child_user_id = 0, int $order_id = 0, int $level = 0, int $rebate_rate = 0)
    {
        self::query()->create([
            'order_id' => $order_id,
            'type' => $type,
            'user_id' => $user_id,
            'child_user_id' => $child_user_id,
            'amount' => $amount,
            'level' => $level,
            'rebate_rate' => $rebate_rate
        ]);
    }

}
